"""配置模块初始化"""

import os
import yaml
import json
from typing import Dict, Any

class ConfigManager:
    """配置管理器，负责加载和管理系统配置"""
    
    def __init__(self):
        self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.config_path = os.path.join(self.base_dir, 'config', 'config.yaml')
        self.camera_config_path = os.path.join(self.base_dir, 'config', 'camera_config.json')
        self.config = self._load_config()
        self.camera_config = self._load_camera_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载主配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            return {}
    
    def _load_camera_config(self) -> Dict[str, Any]:
        """加载摄像头配置文件"""
        try:
            with open(self.camera_config_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"加载摄像头配置失败: {e}")
            return {'cameras': [], 'default_settings': {}}
    
    def get(self, key_path: str, default: Any = None) -> Any:
        """获取配置值，支持嵌套键路径
        
        Args:
            key_path: 配置键路径，如 "detection.confidence_threshold"
            default: 默认值
            
        Returns:
            配置值
        """
        keys = key_path.split('.')
        value = self.config
        
        for key in keys:
            if isinstance(value, dict) and key in value:
                value = value[key]
            else:
                return default
        
        return value
    
    def get_camera_config(self, camera_id: int = None) -> Dict[str, Any]:
        """获取摄像头配置
        
        Args:
            camera_id: 摄像头ID，如果为None则返回所有摄像头配置
            
        Returns:
            摄像头配置
        """
        if camera_id is None:
            return self.camera_config['cameras']
        
        for camera in self.camera_config['cameras']:
            if camera['id'] == camera_id:
                return camera
        
        return {}
    
    def update(self, key_path: str, value: Any) -> bool:
        """更新配置值
        
        Args:
            key_path: 配置键路径
            value: 新值
            
        Returns:
            是否更新成功
        """
        try:
            keys = key_path.split('.')
            config = self.config
            
            # 导航到目标键的父级
            for key in keys[:-1]:
                if key not in config:
                    config[key] = {}
                config = config[key]
            
            # 设置值
            config[keys[-1]] = value
            return True
        except Exception as e:
            print(f"更新配置失败: {e}")
            return False
    
    def save(self) -> bool:
        """保存配置到文件
        
        Returns:
            是否保存成功
        """
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                yaml.dump(self.config, f, default_flow_style=False, allow_unicode=True)
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False

# 创建全局配置管理器实例
config_manager = ConfigManager()

# 导出常用配置方法
def get_config(key_path: str, default: Any = None) -> Any:
    """获取配置的快捷方法"""
    return config_manager.get(key_path, default)

def get_camera_config(camera_id: int = None) -> Dict[str, Any]:
    """获取摄像头配置的快捷方法"""
    return config_manager.get_camera_config(camera_id)